package com.security.Filter.SecurityFilter;

import com.security.Utils.CaptchaUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.session.SessionAuthenticationException;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.context.request.ServletWebRequest;
import org.springframework.web.filter.OncePerRequestFilter;
import org.thymeleaf.util.StringUtils;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 *  图片 验证码 过滤
 *
 */
@Component
public class SecurityCaptchaCodeFilter extends OncePerRequestFilter {

    @Resource
    SecurityFailureHandler failureHandler;

    @Override
    protected void doFilterInternal(HttpServletRequest req, HttpServletResponse res, FilterChain filterChain) throws ServletException, IOException {
        //判断 是否是 login 求情 并且 是 post
        if(StringUtils.equals("/login",req.getRequestURI()) && StringUtils.equalsIgnoreCase(req.getMethod(),"post")){
            try {
                // 获取 httpsession 获取 验证码
                ServletWebRequest servletWebRequest = new ServletWebRequest(req);
                HttpSession session = servletWebRequest.getRequest().getSession();
                String imgcode = session.getAttribute(CaptchaUtils.CAPTCHA_SESSION_KEY).toString();
                //获取 请求 携带的 验证码
                String codeInRequest = ServletRequestUtils.getStringParameter(servletWebRequest.getRequest(),"captcha");
                if(!StringUtils.equals(codeInRequest,imgcode)){
                    //不匹配 抛异常 ，SecurityFailureHandler 处理这个异常
                    throw new SessionAuthenticationException("验证码不匹配");
                }
            }catch (AuthenticationException e){
                failureHandler.onAuthenticationFailure(req,res,e);
                return;
            }
        }
        //如果匹配继续执行 过滤链
        filterChain.doFilter(req,res);
    }
}
